package org.example.demo01.service;

import org.example.demo01.entity.PPlanItem;
import org.example.demo01.entity.Piece;
import org.example.demo01.repository.PPlanItemRepository;
import org.example.demo01.repository.PieceRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class BarcodeService {

    private final PPlanItemRepository pPlanItemRepository;
    private final PieceRepository pieceRepository;

    @Autowired
    public BarcodeService(PPlanItemRepository pPlanItemRepository, PieceRepository pieceRepository) {
        this.pPlanItemRepository = pPlanItemRepository;
        this.pieceRepository = pieceRepository;
    }

    @Transactional
    public Map<String, Object> generatePieces(String pplansheet) {
        // 1. 获取生产计划项
        List<PPlanItem> planItems = pPlanItemRepository.findByPplansheet(pplansheet);
        List<Piece> newPieces = new ArrayList<>();
        List<String> newPieceIds = new ArrayList<>();

        // 2. 为每个产品生成指定数量的条码，先生成所有待插入的件号
        for (PPlanItem item : planItems) {
            for (int i = 1; i <= item.getAmount(); i++) {
                String pieceId = generateBarcode(item, i);
                newPieceIds.add(pieceId);
            }
        }

        // 3. 查询数据库中已存在的件号
        List<Piece> existedPieces = pieceRepository.findAllById(newPieceIds);
        List<String> existedIds = new ArrayList<>();
        for (Piece existed : existedPieces) {
            existedIds.add(existed.getId());
        }

        // 4. 只插入数据库中不存在的件号
        for (PPlanItem item : planItems) {
            for (int i = 1; i <= item.getAmount(); i++) {
                String pieceId = generateBarcode(item, i);
                if (!existedIds.contains(pieceId)) {
                    Piece piece = new Piece();
                    piece.setId(pieceId);
                    piece.setPid(item.getPid());
                    newPieces.add(piece);
                }
            }
        }

        // 5. 批量保存到数据库
        pieceRepository.saveAll(newPieces);

        // 6. 统计每个产品的计划总数、已生成数、还需生产数
        List<Map<String, Object>> productStats = new ArrayList<>();
        for (PPlanItem item : planItems) {
            String pid = item.getPid();
            int planTotal = item.getAmount();
            // 统计该产品已生成的件数
            int produced = 0;
            for (String pieceId : newPieceIds) {
                if (existedIds.contains(pieceId) || newPieces.stream().anyMatch(p -> p.getId().equals(pieceId))) {
                    // 只统计属于该产品的件号
                    if (pieceId.contains(pid)) {
                        produced++;
                    }
                }
            }
            int needProduce = planTotal - produced;
            Map<String, Object> stat = new HashMap<>();
            stat.put("pid", pid);
            stat.put("planTotal", planTotal);
            stat.put("produced", produced);
            stat.put("needProduce", needProduce < 0 ? 0 : needProduce);
            productStats.add(stat);
        }

        // 7. 返回新生成、已存在工件列表和统计信息
        Map<String, Object> result = new HashMap<>();
        result.put("newPieces", newPieces);
        result.put("existedPieces", existedPieces);
        result.put("productStats", productStats);
        return result;
    }

    private String generateBarcode(PPlanItem item, int sequence) {
        return String.format("%s-%s-%03d",
                item.getPplansheet(),
                item.getPid(),
                sequence);
    }
}
